#include "FileInterface.h"

using namespace std;

//Record Fns
void FileInterface::add_record(Data _Data){
	this->records.push_back(_Data);
}

void FileInterface::del_record(int _index){
	this->records.erase(this->records.begin()+_index);
}

//File Fns
void FileInterface::set_file(string _filename){
	this->filename = _filename;
}

string FileInterface::get_file(){
	return this->filename;
}

int FileInterface::read_file(){
	file.open(this->filename.c_str(),ios::in);
	if(!file.is_open()){
		//cout << "Error in opening " << this->filename.c_str() << "! Please check file exists!\n";
		this->clear_file();

		return -1;
	} else {
		//Read contents
		char* temp = new char[1000];
		Data* d_temp;
		while(!file.eof()){
			file.getline(temp,1000,'\n');
			if(strcmp(temp,"")!=0){
				d_temp = new Data(temp);
				this->add_record(*d_temp);
			}
		}

		file.close();
	}
	return 0;
}

int FileInterface::write_file(){
	//OPen file and truncate, rewrite all contents.
	file.open(this->filename.c_str(),std::fstream::out|std::fstream::trunc);
	if(!file.is_open()){
		cout << "Error in opening " << this->filename.c_str() << "! Please check file exists!\n";
		return -1;
	} else {
		//Write contents
		for(int i=0 ; i<this->records.size() ; i++){
			file << records[i].get_message().c_str() << "\n";
		}
		file.close();
	}
	return 0;
}

int FileInterface::clear_file(){
	file.open(this->filename.c_str(),std::fstream::out|std::fstream::trunc);
	file.close();
	return 0;
}

//Display Fns
void FileInterface::print_records(){
	for(unsigned int i=0 ; i<this->records.size() ; i++){
		cout << i+1 << ". " << this->records[i].toString() << "\n";
	}
}
